package com.sdcqjy.property.home.fragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.sdcqjy.mylibrary.FileOperateUtil;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.mylibrary.http.DownloadCallBack;
import com.sdcqjy.mylibrary.http.DownloadDB;
import com.sdcqjy.mylibrary.http.DownloadManage;
import com.sdcqjy.mylibrary.http.DownloadMode;
import com.sdcqjy.mylibrary.http.DownloadTask;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.BaseFragment;
import com.sdcqjy.property.mode.ListMsgMode;
import com.sdcqjy.property.presenter.contract.a;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by 磁磁帅 on 2018/4/27.
 * 功能：
 */
public class PdfFragment extends BaseFragment implements DownloadCallBack {
    @BindView(R.id.layoutTitle)
    RelativeLayout layoutTitle;
    @BindView(R.id.fl)
    FrameLayout fl;
    Unbinder unbinder;
    private DownloadTask downloadTask;
    private ListMsgMode mode;
    private ProgressDialog progressDialog;
    private String wordUrl;
    private String path;

    public static PdfFragment newInstance(ListMsgMode mode) {
        Bundle bundle = new Bundle();
        bundle.putParcelable("mode", mode);
        PdfFragment fragment = new PdfFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_word, null);
        unbinder = ButterKnife.bind(this, view);
        layoutTitle.setVisibility(View.GONE);
        return view;
    }

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        mode = bundle.getParcelable("mode");

        if (mode != null) {
            wordUrl = mode.htmlPath;
            checkSDCardPermission();
        }
    }

    private void checkSDCardPermission() {
        if (ContextCompat.checkSelfPermission(getActivity()
                , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            downloadFile();
        } else {
            PermissionGen.with(getActivity())
                    .addRequestCode(200)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        }
    }

    /**
     * 打开文件
     */
    private void openFile(String path) {
        this.path = path;
        String[] split = path.split("\\.");
        TbsReaderView readerView = new TbsReaderView(getActivity(), new TbsReaderView.ReaderCallback() {
            public void onCallBackAction(Integer integer, Object o, Object o1) {
            }
        });
        mTbsReaderView = readerView;
        //通过bundle把文件传给x5,打开的事情交由x5处理
        Bundle bundle = new Bundle();
        //传递文件路径
        bundle.putString("filePath", path);
        //加载插件保存的路径
        bundle.putString("tempPath", Environment.getExternalStorageDirectory() + File.separator + "temp");
        //加载文件前的初始化工作,加载支持不同格式的插件
        boolean b = readerView.preOpen(split[split.length - 1], false);
        if (b) {
            readerView.openFile(bundle);
        }
        fl.addView(readerView);
    }

    private TbsReaderView mTbsReaderView;

    public void onDestroyView() {
        super.onDestroyView();
        if (mTbsReaderView != null) mTbsReaderView.onStop();
        DownloadManage.getInstance().removeCallBack(this);
        unbinder.unbind();
    }

    @PermissionSuccess(requestCode = 200)
    public void doSDLoadSuccess() {
        downloadFile();
    }

    @PermissionFail(requestCode = 200)
    public void doSDLoadFail() {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.tishi)
                .setMessage(R.string.ylwd_qxts)
                .setPositiveButton(R.string.congxinhuoqu, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        checkSDCardPermission();
                    }
                })
                .setNeutralButton(R.string.shoudonghuoqu, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        OtherUtils.startAppDetailSettingIntent(getActivity());
                    }
                }).show();
    }

    private void downloadFile() {
        String url;
        if (wordUrl.startsWith("http")) {
            url = wordUrl;
        } else url = a.FileHost + wordUrl;
        downloadTask = new DownloadTask(DownloadTask.DownloadTypeStart, url);
        downloadTask.setDownloadCallBack(this);
        String name = downloadTask.getName();
        DownloadDB db = new DownloadDB(getActivity());
        List<DownloadMode> modeList = db.getTaskOfName(name);
        db.close();
        String fileName = FileOperateUtil.getFileNameOfUrl(downloadTask.getUrl());
        downloadTask.path = FileOperateUtil.getInstance().getFolderPath(FileOperateUtil.TYPE_TEXT);
        String path = downloadTask.path + fileName;
        if (modeList == null || modeList.size() == 0) {
            File file = new File(path);
            if (file.exists()) openFile(path);
            else {
                DownloadManage.getInstance().executionTask(downloadTask);
                openDialog();
            }
        } else {
            DownloadManage.getInstance().executionTask(downloadTask);
            openDialog();
        }
    }

    private void openDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMax(100);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.quxiao), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                progressDialog = null;
                if (downloadTask != null) {
                    downloadTask.setType(DownloadTask.DownloadTypePause);
                    DownloadManage.getInstance().executionTask(downloadTask);
                }
                getActivity().onBackPressed();
            }
        });
    }

    public void inProgress(DownloadMode mode) {
        if (progressDialog == null) return;
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        long l = mode.currLen * 100 / mode.total;
        progressDialog.setProgress((int) l);
    }

    public void onError(DownloadMode mode) {
        ShowToast.alertShortOfWhite(getActivity(), R.string.xiazaishibai);
        if (progressDialog == null) return;
        progressDialog.dismiss();
        progressDialog = null;
    }

    public void onStop(DownloadMode mode) {
    }

    public void onResponse(DownloadMode mode) {
        if (progressDialog == null) return;
        progressDialog.dismiss();
        progressDialog = null;
        openFile(mode.path);
    }
}
